<template>
  <div class="customer-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户信息管理</span>
          <el-button type="primary" @click="handleAdd">添加客户</el-button>
        </div>
      </template>

      <el-table :data="customerList" style="width: 100%">
        <el-table-column prop="id" label="客户ID" width="100" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="cartNumber" label="身份证号" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rentalCount" label="租车次数" width="100" />
        <el-table-column prop="lastRental" label="最近租车" width="180" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加客户' : '编辑客户'"
      width="500px"
    >
      <el-form :model="customerForm" label-width="100px" :rules="rules" ref="customerFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="customerForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="customerForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="身份证号" prop="cartNumber">
          <el-input v-model="customerForm.cartNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="customerForm.status" placeholder="请选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="黑名单" value="黑名单" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api/auth'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const customerList = ref([])

// 获取客户列表数据
const fetchCustomerList = async () => {
  try {
    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    console.log('发送请求到:', 'http://localhost:8080/customers/list')
    console.log('请求参数:', {
      page: currentPage.value,
      size: pageSize.value
    })
    console.log('请求头:', {
      'Token': token,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    })

    const response = await api.get(`/customers/list`, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Token': token,
        'Content-Type': 'application/json'
      },
      withCredentials: true
    })
    
    console.log('响应数据:', response)
    
    if (response.code === 200) {
      // 更新数据结构处理
      customerList.value = response.data.records.map(customer => ({
        id: customer.id,
        name: customer.name,
        phone: customer.phone,
        cartNumber: customer.cartNumber,
        status: customer.status === 1 ? '正常' : '黑名单',
        rentalCount: customer.rentalTimes,
        lastRental: customer.latelyRentalTime
      }))
      // 更新分页信息
      total.value = response.data.total
      currentPage.value = response.data.current
      pageSize.value = response.data.size
    } else {
      ElMessage.error(response.message || '获取客户列表失败')
    }
  } catch (error) {
    console.error('获取客户列表错误:', error)
    console.error('错误详情:', {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      headers: error.response?.headers,
      data: error.response?.data,
      config: error.config
    })
    ElMessage.error('获取客户列表失败，请检查网络连接')
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCustomerList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCustomerList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCustomerList()
})

const dialogVisible = ref(false)
const dialogType = ref('add')
const customerFormRef = ref(null)
const customerForm = reactive({
  name: '',
  phone: '',
  cartNumber: '',
  status: '正常'
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  cartNumber: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(customerForm, {
    name: '',
    phone: '',
    cartNumber: '',
    status: '正常'
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(customerForm, {
    id: row.id,
    name: row.name,
    phone: row.phone,
    cartNumber: row.cartNumber,
    status: row.status
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该客户吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    console.log('发送删除请求到:', `http://localhost:8080/customers/delete/${row.id}`)

    const response = await api.delete(`/customers/delete/${row.id}`, {
      headers: {
        'Token': token,
        'Content-Type': 'application/json'
      }
    })
    
    console.log('删除响应:', response)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 刷新客户列表
      fetchCustomerList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客户错误:', error)
      console.error('错误详情:', {
        message: error.message,
        status: error.response?.status,
        data: error.response?.data
      })
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

const handleSubmit = async () => {
  if (!customerFormRef.value) return
  
  try {
    await customerFormRef.value.validate()
    
    const token = localStorage.getItem('Token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    // 转换状态值为整数
    const { id, name, phone, cartNumber, status } = customerForm
    const submitData = {
      name,
      phone,
      cartNumber,
      status: status === '正常' ? 1 : 2
    }

    // 如果是编辑模式，添加 id
    if (dialogType.value === 'edit' && id) {
      submitData.id = id
    }

    console.log('发送请求到:', 'http://localhost:8080/customers/add')
    console.log('请求数据:', submitData)

    const response = await api.post('/customers/add', submitData, {
      headers: {
        'Token': token,
        'Content-Type': 'application/json'
      }
    })
    
    console.log('响应数据:', response)
    
    if (response.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
      dialogVisible.value = false
      // 刷新客户列表
      fetchCustomerList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单错误:', error)
    console.error('错误详情:', {
      message: error.message,
      status: error.response?.status,
      data: error.response?.data
    })
    ElMessage.error('操作失败，请检查网络连接')
  }
}

const getStatusType = (status) => {
  return status === '正常' ? 'success' : 'danger'
}
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 